<template>
  <div>
    <!--    面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片视图-->
    <el-card class="box-card">
      <el-row>
        <el-button type="primary" >添加角色</el-button>
      </el-row>

<!--      角色列表区-->
      <el-table
        :data="roleList"
        border
        stripe
        style="width: 100%">
<!--        展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['y-center','bd-bottom',i1==0?'bd-top':'']"   v-for="(lv1,i1) in scope.row.children" :key="lv1.id">
<!--              渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="delRightById(scope.row,lv1.id)">{{lv1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              渲染二三级权限-->
              <el-col :span="19">
<!--                通过嵌套for循环渲染二级权限-->
                <el-row :class="['y-center',i2==0?'':'bd-top']" v-for="(lv2,i2) in lv1.children" :key="lv2.id">
<!--                  二级权限-->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="delRightById(scope.row,lv2.id)">{{lv2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
<!--                  三级权限-->
                  <el-col :span="18">
                    <el-tag type="warning" @close="delRightById(scope.row,lv3.id)" closable v-for="lv3 in lv2.children" :key="lv3.id">{{lv3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
<!--        索引类-->
        <el-table-column type="index" label="#"/>
        <el-table-column prop="roleName" label="角色名称"/>
        <el-table-column prop="roleDesc" label="角色描述"/>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

<!--  分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="toggleRightDialogShow"
      width="50%">
<!--   树形控件-->
<!--      ref=treeRef是我们自己添加引用,我们用this.$refs.treeRef拿到这个对象-->
      <el-tree
        ref=treeRef
        :data="rightsList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkedRights"
        :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="toggleRightDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="assignPermissions()">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 是否显示对话框
      toggleRightDialogShow: false,
      // 角色列表
      roleList: null,
      // 所以权限列表
      rightsList: null,
      checkedRights: null,
      // 要修改权限的角色id
      roleId: '',
      // 属性对象的属性绑定对象
      defaultProps: {
        children: 'children',
        label: 'authName'
      }

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$msg.error(res.meta.msg)
        return false
      }
      this.roleList = res.data
      // console.log(this.roleList)
    },
    // 根据id删除对应的权限
    async delRightById(role, rightId) {
      // 弹框确认删除
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$msg.info('取消了删除')
      }
      // 确认删除
      const res = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      role.children = res.data
    },
    // 展示所有权限,并默认选中该角色的权限
    async showRightsDialog(role) {
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.rightsList = res.data
      // 保存id,修改id的时候使用
      this.roleId = role.id
      this.checkedRights = []
      this.getLv3Id(role, this.checkedRights)
      this.toggleRightDialogShow = true
    },
    // 获取所有三级权限的id,并保持到checkedRights
    getLv3Id(node, arr, i = 0) {
      // 确保只拿第三级权限的id
      if (i++ === 3) {
        return arr.push(node.id)
      }
      if (node.children == null) {
        return
      }
      node.children.forEach(item => {
        this.getLv3Id(item, arr, i)
      })
      // 特殊数据结构,如果没有二级菜单,一级菜单的children是空数组
      // 三级没有同理
      // if (!node.children) {
      //   return arr.push(node.id)
      // }
      // node.children.forEach(item => {
      //   this.getLv3Id(item, arr)
      // })
    },
    // 点击为确实分配权限
    async assignPermissions() {
      // 合并数组
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]

      const rids = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleId}/rights`, { rids })
      if (res.meta.status !== 200) {
        this.$msg.error(res.meta.msg)
        return false
      }
      this.$msg.success(res.meta.msg)
      this.getRoleList()
      this.toggleRightDialogShow = false

    }
  }
}
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }
  .bd-top {
    border-top: 1px solid #eeeeee;
  }
  .bd-bottom {
    border-bottom: 1px solid #eeeeee;
  }
  /*纵向居中对齐*/
  .y-center {
    display: flex;
    align-items: center;
  }
</style>
